<?php

namespace app\admin\controller\goods;

use app\admin\model\GoodsParams;
use app\admin\model\GoodsSpec;
use app\admin\model\GoodsSpecValue;
use app\admin\model\GoodsType;
use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Type extends Backend
{
    
    /**
     * GoodsType模型对象
     * @var \app\admin\model\GoodsType
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\GoodsType;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['typeParams','typeSpec'])
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['typeParams','typeSpec'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);

                    $this->assemble();
                    //中间表 关联
                    //$this->model->typeParams()->attach([1,2]);
                    //$this->model->typeSpec()->attach([1,2]);

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 组装 params和type 保存属性
     */
    protected function assemble(){

        $requestData = $this->request->param();

        $params_name = $requestData['params_name'];

        $paramsData = [];
        foreach ($params_name as $key => $val) {
            if ($val) {
                $paramsData[$key]['id'] = $requestData['params_id'][$key];
                $paramsData[$key]['name'] = $requestData['params_name'][$key];
                $paramsData[$key]['type'] = $requestData['params_type'][$key];
                $paramsData[$key]['value'] = $requestData['params_value'][$key];
            }
        }
        //属性值
        $typeSpecData = [];
        $type_name = input('post.type_name/a', []);
        foreach ($type_name as $key => $val) {
            if ($val) {
                $typeSpecData[$key]['id'] = $requestData['type_id'][$key];
                $typeSpecData[$key]['name'] = $requestData['type_name'][$key];
                $typeSpecData[$key]['weigh'] = $requestData['type_sort'][$key];
                $typeSpecData[$key]['value'] = explode(' ', $requestData['type_value'][$key]);
            }
        }


        //保存参数
        $pIds = [];
        if ($paramsData) {
            $goodsParamsModel = new GoodsParams();
            foreach ($paramsData as $key => $val) {
                if ($val['id']) {
                    $goodsParamsModel->where(
                        ['id' => $val['id']
                        ])->update($val);
                } else {
                    unset($val['id']);
                    $res       = $goodsParamsModel->save($val);
                    $val['id'] = $goodsParamsModel->id;
                }
                $pIds[] = $val['id'];
            }
            //多对多关联
            $this->model->typeParams()->attach(array_unique($pIds));
        }

        //保存属性
        $sIds        = [];
        $goodsSpecValue = new GoodsSpecValue();
        //$goodsSpec = new GoodsSpec();
        if ($typeSpecData) {
            foreach ($typeSpecData as $key => $value) {
                //TODO new GoodsSpec 在foreach 循环外面 用的是同一个实例，save更新添加有点麻烦 ，new 放在foreach中，用的是不同实例
                $goodsSpec = new GoodsSpec();
                if ($value['id']) {
                    //更新属性
                    //$goodsSpec->update($value, ['id' => $value['id']],'id,name,weigh');
                    $goodsSpec->allowField(true)->save($value, ['id' => $value['id']]);
                    //删除原属性值
                    $goodsSpecValue->where([
                        'spec_id' => $value['id']
                    ])->delete();
                    //添加属性值
                    $specValue     = $value['value'];
                    $tempSpecValue = [];
                    foreach ($specValue as $sk => $sv) {
                        $tempSpecValue[] = [
                            'spec_id' => $value['id'],
                            'value'   => $sv,
                        ];
                    }
                    $goodsSpecValue->saveAll($tempSpecValue);
                } else {
                    //去掉空id
                    unset($value['id']);
                    $res           = $goodsSpec->allowField(true)->save($value);
                    $value['id']   = $goodsSpec->id;
                    $specValue     = $value['value'];
                    $tempSpecValue = [];
                    foreach ($specValue as $sk => $sv) {
                        $tempSpecValue[] = [
                            'spec_id' => $value['id'],
                            'value'   => $sv,
                        ];
                    }
                    $goodsSpecValue->saveAll($tempSpecValue);
                }
                $sIds[] = $value['id'];
            }
            //多对多关联
            $this->model->typeSpec()->attach(array_unique($sIds));
        }

        //echo '<pre>';
        //var_dump($typeSpecData);exit;

        return true;
    }

    /**
     * 获取和设置参数
     * @return array|string
     * @throws \think\Exception
     */
    public function addParams()
    {
        $id = $this->request->request('id');

        $goodsType = GoodsType::get($id);

        $typeParams = $goodsType->typeParams()->select();

        if (!$goodsType) {
            $this->error('错误操作！'); //todo 统一错误页面
        }
        //获取类型名称
        $this->assign('spec_name', $goodsType['name']);
        $this->assign('spec_id', $goodsType['id']);

        //获取全部属性
        $goodsParamsModel = new GoodsParams();
        $params = $goodsParamsModel->select();
        $this->assign('params', $params);

        //获取已绑定参数

        $typePids = [];
        if ($typeParams) {
            $typePids = array_column($typeParams, 'id');
        }
        $this->assign('typePids', $typePids);


        if ($this->request->isPost()) {

            $params_id = $this->request->request('params_id/a');
            //删除旧关联
            $goodsType->typeParams()->detach();
            //绑定新关联
            $goodsType->typeParams()->attach($params_id);

            $this->success('关联成功');
        }
        return $this->view->fetch();
    }

    /**
     * 商品类型关联属性
     * @return string
     * @throws \think\Exception
     */
    public function addSpec()
    {
        $id = $this->request->request('id');

        $goodsType = GoodsType::get($id);

        $typeSpec = $goodsType->typeSpec()->select();

        if (!$goodsType) {
            $this->error('错误操作！'); //todo 统一错误页面
        }
        //获取类型名称
        $this->assign('spec_name', $goodsType['name']);
        $this->assign('spec_id', $goodsType['id']);

        //获取全部属性
        $typeSpecModel = new GoodsSpec();
        $specList = $typeSpecModel->select();
        $this->assign('specList', $specList);

        //获取已关联属性
        $this->assign('typeSpec', $typeSpec);
        $typeSids = [];
        if ($typeSpec) {
            $typeSids = array_column($typeSpec, 'id');
        }
        $this->assign('typeSids', $typeSids);

        if ($this->request->isPost()) {

            $spec_id = $this->request->request('spec_id/a');
            //删除旧关联
            $goodsType->typeSpec()->detach();
            //绑定新关联
            $goodsType->typeSpec()->attach($spec_id);

            $this->success('关联成功');
        }

        return $this->view->fetch();
    }

}
